const axios = require('axios')
const {webPort, streamPort} = require('../config')
const {exec} = require('child_process')
const Camera = require('../model/camera')
const { Op } = require("sequelize")
class RunStream {
    constructor(id, url) {
        this.id = id;
        this.url = url
        let rmtpUrl = `rtmp:localhost:${streamPort}/live/${id}`
        this.path = `ffmpeg -rtsp_transport tcp -i ${url} -c copy -f flv ${rmtpUrl}`
    }

    async run() {
        await this.setCameraStatus(10)
        this.ls = exec(this.path, (error, stdout, stderr) => {

        })
        this.ls.on('exit', this.processExit.bind(this))
        this.ls.on('close', this.processClose.bind(this))
    }

    async processExit() {
        console.log('流异常退出！')
        await this.setCameraStatus(20)
    }

    async processClose(){

    }

    async setCameraStatus(status) {
        let camera = await Camera.findByPk(this.id)
        camera.status = status
        await camera.save({fields: ['status']})
    }

}

class LiveStreamService {
    async checkHealth() {
        const url = `http://127.0.0.1:${webPort}/api/streams`
        let response = await axios.get(url)
        let cameras = await Camera.findAll()
        let ids = cameras.map(s=>s.id)
        let liveIds = response.data.live?this.getIds(response.data.live):[]
        let offLineIds = ids.filter(s=>!liveIds.includes(s))
        if(offLineIds.length >0){
            await Camera.update({status:20},{
                where:{
                    id:offLineIds
                }
            })
        }
        if(liveIds.length>0){
            await Camera.update({status:10},{
                where:{
                    id:liveIds
                }
            })
        }
    }

    getIds(data){
        let ids = []
        for(var i in data){
            ids.push(i)
        }
        return ids
    }

    connect(camera) {
        let {id, url} = camera
        let stream = new RunStream(id, url)
        stream.run()
    }

}

module.exports = new LiveStreamService()